<?php
class CMS_Controller_Plugin_Language extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        try
        {
            if (! Zend_Session::isStarted ())
                Zend_Session::start ();
            $session = new Zend_Session_Namespace ( 'language' );
        }
        catch ( Zend_Session_Exception $e )
        {
            echo "Cannot instantiate this namespace since \$myIdSession was created\n";
        }
        
        $lang = $request->getParam ( 'lang', null );
        $local = Zend_Registry::get('Zend_Locale');
        if($lang != 'en' && $lang != 'vi' ) {
        	$lang = null;
        }
              
        if (! $lang)
        {        
            // get lang  from session                               
            if (! isset ( $session->current_lang ))
            { 
            	// not set language in session
            	$lang = $local->getLanguage();
                if ($session->isLocked ()) //unlock sessiong language
                    $session->unlock ();
                $session->current_lang = $lang;
            }
            else
            {
                $lang = $session->current_lang;
            }
             
        }
        else
        {
            if ($session->isLocked ()) //unlock sessiong language
                $session->unlock ();
                // set language to session                              
            $session->current_lang = $lang;         
        }
      
        $session->setExpirationSeconds ( 1 * 60 * 60 * 12 );
        $session->lock ();
        
        $translate = Zend_Registry::get('Zend_Translate');
        $translate->setLocale($lang);
        Zend_Registry::set('Zend_Translate',$translate);
        
        $request->setParam('lang',$lang);
    }
}